package com.video.main_video.manager.handle.login;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.redis.handler.RedisServiceImp;
import com.video.main_video.common.jwt.JwtUtils;
import com.video.main_video.common.staticData.StaticData;
import com.video.main_video.dao.entity.User;
import com.video.main_video.dao.request.LoginRequest;
import com.video.main_video.dao.response.LoginResponse;
import com.video.main_video.manager.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service
public class LoginManger {
//    @Autowired
//    RedisServiceImp redisServiceImp;

    @Autowired
    UserMapper userMapper;

    public String token="";

    private String userId="";

    private String userName;

    public LoginResponse login(LoginRequest loginRequest) {
        LoginResponse res = new LoginResponse();
        boolean verifyResult= verifyUser(loginRequest);
        if(!verifyResult){
            res.setCode(203);
            res.setMsg("userName or password incorrect");
            return res;
        }
        res.setCode(200);
        res.setMsg("login successful");
        res.setUserId(userId);
        StaticData.UserId=userId;
        res.setUserName(userName);
        Map<String, String> map = new HashMap<>();
        map.put("userName", loginRequest.getUserName());
        map.put("password", loginRequest.getPassword());
        map.put("userId",this.userId);
        token= JwtUtils.getToken(map);
//        redisServiceImp.cacheValue("admin",token);
        return res;
    }

    private boolean verifyUser(LoginRequest loginRequest){
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<User>();
        qw.eq(User::getUserName,loginRequest.getUserName()).eq(User::getPassword,loginRequest.getPassword());
        User user = userMapper.selectOne(qw);
        if(user==null){
            return false;
        }
        userId=user.getId();
        userName=user.getUserName();
        return true;
    }

}
